package com.jiangyifen.robot.core.asr;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.idst.nls.realtime.NlsClient;
import com.alibaba.idst.nls.realtime.NlsFuture;
import com.alibaba.idst.nls.realtime.event.NlsEvent;
import com.alibaba.idst.nls.realtime.event.NlsListener;
import com.alibaba.idst.nls.realtime.protocol.NlsRequest;
import com.alibaba.idst.nls.realtime.protocol.NlsResponse;
import com.alibaba.idst.nls.realtime.protocol.NlsResponse.Result;
import com.jiangyifen.robot.core.Robot;
import com.jiangyifen.robot.sdk.event.HumanSentenceCompleteEvent;
import com.jiangyifen.robot.sdk.event.HumanSpeakingEvent;


/**
 * 
 * @author yifen.jiang
 *
 */
public class AliyunASRClient implements NlsListener {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private NlsClient client;

	private Robot robot;

	/**
	 * asr相关配置
	 */
	public AliyunASRClient() {
		client = new NlsClient();
		client.init();
	}

	public void startup() {
		client.init();
	}

	public void shutdonw() {
		client.close();
	}

	public void process(InputStream inputStream) {
		new Thread(() -> {

			logger.info("开始ASR语音识别...");
			try {
				NlsRequest req = buildRequest(robot.getRobotEntity().getAsrVocabularyId());
				NlsFuture future = client.createNlsFuture(req, this);

				byte[] b = new byte[8000];
				int len;
				while ((len = inputStream.read(b)) > 0) {
					future.sendVoice(b, 0, len);
				}

				future.sendFinishSignal();

				future.await(100000);

			} catch (IOException e) {
				logger.debug("asr inputStream closed");
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

		}).start();
	}

	private NlsRequest buildRequest(String vocabularyId) {
		NlsRequest req = new NlsRequest();
		req.setAppkey(robot.getRobotEntity().getAsrAppKey());
		req.setFormat(robot.getRobotEntity().getAsrFormat());
		req.setResponseMode(robot.getRobotEntity().getAsrResponseMode());
		req.setSampleRate(robot.getRobotEntity().getAsrSampleRate());
		req.authorize(robot.getRobotEntity().getAliyunAccessId(), robot.getRobotEntity().getAliyunAccessSecret());

		// 用户根据[热词文档](~~49179~~) 设置自定义热词。
		// 通过设置VocabularyId调用热词。
		// if(StringUtils.isNotBlank(vocabularyId)){
		// req.setVocabularyId(vocabularyId);
		// System.out.println(vocabularyId);
		// }

		// 设置关键词库ID 使用时请修改为自定义的词库ID
		// String request = "{\n" + " \"keywords\": [\n" + "
		// {\"keyword\":\"身份证\", \"threshold\":0},\n"
		// + " {\"keyword\":\"您好\", \"threshold\":0}\n" + " ]\n" + "}";
		// String response = KwsMngUtil.create(ak_id, ak_secret, request);
		// System.out.println(response);
		// String keywordListId = (String) JSONPath.read(response,
		// "$.keyword_list_id");
		// req.setKeyWordListId(keywordListId);

		return req;

	}

	private void fireASRSentenceEvent(NlsEvent nlsEvent) {

		try {

			HumanSentenceCompleteEvent event = new HumanSentenceCompleteEvent();
			NlsResponse response = nlsEvent.getResponse();
			if (response == null) {
				return;
			}
			Result result = response.getResult();
			if (result == null) {
				return;
			}
			
			event.setConversationId(response.getRequestId());
			event.setSentenceId(result.getSentence_id());
			event.setStatusCode(result.getStatus_code());
			event.setBeginTime(result.getBegin_time());
			event.setEndTime(result.getEnd_time());
			event.setText(result.getText());
			event.setRobotId(robot.getId());

			robot.onHumanSentenceComplete(event);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	}
	
	private void fireASRSpeakingEvent(NlsEvent nlsEvent) {

		try {

			HumanSpeakingEvent event = new HumanSpeakingEvent();
			NlsResponse response = nlsEvent.getResponse();
			if (response == null) {
				return;
			}
			Result result = response.getResult();
			if (result == null) {
				return;
			}
			
			if(StringUtils.isBlank(result.getText())){
				return;
			}
			
			event.setConversationId(response.getRequestId());
			event.setSentenceId(result.getSentence_id());
			event.setStatusCode(result.getStatus_code());
			event.setBeginTime(result.getBegin_time());
			event.setEndTime(result.getEnd_time());
			event.setText(result.getText());
			event.setRobotId(robot.getId());

			robot.onHumanSpeaking(event);
			
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	}

	@Override
	public void onMessageReceived(NlsEvent e) {
		logger.debug("ASR onMessageReceived: " + JSON.toJSONString(e));
		// 说话event
		fireASRSpeakingEvent(e);

		// 完整句子event
		NlsResponse response = e.getResponse();
		if (response.result != null && response.result.getStatus_code() == 0) {
			fireASRSentenceEvent(e);
		}

	}

	@Override
	public void onOperationFailed(NlsEvent e) {
		logger.debug("ASR onOperationFailed: " + JSON.toJSONString(e));
	}

	@Override
	public void onChannelClosed(NlsEvent e) {
		logger.debug("ASR onChannelClosed: " + JSON.toJSONString(e));
	}

	public Robot getRobot() {
		return robot;
	}

	public void setRobot(Robot robot) {
		this.robot = robot;
	}

}